<?php

namespace App\GraphQL\Queries\Group;

use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Facades\DB;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Querys
{
    /**
     * Return a value for the field.
     *
     * @param  null  $rootValue Usually contains the result returned from the parent field. In this case, it is always `null`.
     * @param  mixed[]  $args The arguments that were passed into the field.
     * @param  \Nuwave\Lighthouse\Support\Contracts\GraphQLContext  $context Arbitrary data that is shared between all fields of a single query.
     * @param  \GraphQL\Type\Definition\ResolveInfo  $resolveInfo Information about the query itself, such as the execution state, the field name, path to the field from the root, and more.
     * @return mixed
     */
    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        $authUser = auth()->user();
        $data = $args['input'];
        $select = 'day as date,SUM(amount) as value';
        if ($data['group'] === 'year') {
            $select = 'DATE_FORMAT(day,"%Y-%m") as date,SUM(amount) as value';
        }
        $items = DB::table('admin_profit_reports')->wheree('user_id',$authUser->id)->whereBetween('day',[$data['start_date'],$data['end_date']])
        ->selectRaw($select)
        ->groupBy('date')->get();
        // 遍历创建中文标题
        $items = $items->map(function($item) use(&$data){
            $title = '';
            return [
                'title'=>$title,
                'value'=>$item->value
            ];
        });
        return [
            'items'=>$items
        ];
    }
}
